package com.demonzym.framework.net;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class ImageDownloadListener implements HttpTaskCallBack {
	
	private Handler mHandler;
	private ImageCallBack mImageCallBack;
	
	public ImageDownloadListener(ImageCallBack callback){
		mImageCallBack = callback;
		if(Looper.myLooper() == null){
			mHandler = new InternalHandler(Looper.getMainLooper());
		}
		else{
			mHandler = new InternalHandler(Looper.myLooper());
		}
	}
	
	@Override
	public void TaskEnd(boolean success) {
		
	}
	
	@Override
	public void TaskEnd(boolean success, Object o) {
		postTaskEnd(success, (Bitmap)o);
	}

	@Override
	public void downloadProcess(int max, int progress) {
		postDownloadProcess(max, progress);
	}

	@Override
	public void uploadProcess(int max, int progress) {
		
	}	


	private void postTaskEnd(boolean success, Bitmap bmp) {		
		mHandler.obtainMessage(IMAGE_DOWNLOAD_END, bmp).sendToTarget();
	}

	private void postDownloadProcess(int max, int progress) {		
		mHandler.obtainMessage(IMAGE_DOWNLOADING_PROGRESS, max, progress).sendToTarget();
	}
	
	public interface ImageCallBack{
		public void getBitmap(Bitmap end);
		public void taskEnd(boolean success);
		public void downloadProcess(int max, int progress);
	}
	
	private static final int IMAGE_DOWNLOAD_END = 0x1;
	private static final int IMAGE_DOWNLOAD_SUCCESS = 0x2;
	private static final int IMAGE_DOWNLOADING_PROGRESS = 0x3;
	private class InternalHandler extends Handler {
		public InternalHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case IMAGE_DOWNLOAD_END:
				mImageCallBack.getBitmap((Bitmap) msg.obj);
				break;				
			case IMAGE_DOWNLOADING_PROGRESS:
				mImageCallBack.downloadProcess(msg.arg1, msg.arg2);
				break;
			case IMAGE_DOWNLOAD_SUCCESS:
				mImageCallBack.taskEnd((Boolean) msg.obj);
			}
			super.handleMessage(msg);
		}
	}

}
